<?php

namespace app\controller;

use app\model\DrawRecord;
use app\model\Prize;
use app\model\User;
use support\Request;
use support\Response;

class DrawController
{
    /**
     * 执行抽奖（单活动模式）
     */
    public function draw(Request $request): Response
    {
        $round = $request->post('round');

        if (!$round) {
            // 如果没有指定轮次，获取最大轮次+1
            $round = Prize::max('round') + 1;
        }

        // 获取该轮次的奖品
        $prizes = Prize::where('round', $round)->select();
        if (empty($prizes)) {
            return json(['code' => 400, 'message' => '该轮次没有设置奖品']);
        }

        // 获取未中奖用户数量
        $nonWinnersCount = User::getNonWinnersCount();
        if ($nonWinnersCount <= 0) {
            return json(['code' => 400, 'message' => '没有可抽奖用户']);
        }

        // 计算奖品总数
        $totalPrizes = 0;
        foreach ($prizes as $prize) {
            $totalPrizes += $prize->quantity;
        }

        // 如果奖品数量超过未中奖用户数量，调整奖品数量
        if ($totalPrizes > $nonWinnersCount) {
            $totalPrizes = $nonWinnersCount;
        }

        // 获取所有未中奖用户
        $nonWinners = User::where('is_winner', 0)->select();
        $winnerIds = [];
        $results = [];

        // 随机选择中奖用户
        for ($i = 0; $i < $totalPrizes && count($nonWinners) > 0; $i++) {
            $randomIndex = mt_rand(0, count($nonWinners) - 1);
            $winner = $nonWinners[$randomIndex];

            // 标记用户为中奖
            $winner->is_winner = 1;
            $winner->save();

            // 获取对应的奖品
            $prizeIndex = $i % count($prizes);
            $prize = $prizes[$prizeIndex];

            // 记录抽奖结果
            DrawRecord::recordDraw($winner->id, $prize->id, $round);

            // 添加到结果中
            $results[] = [
                'user' => $winner,
                'prize' => $prize
            ];

            // 从非中奖列表中移除
            array_splice($nonWinners, $randomIndex, 1);
        }

        return json([
            'code' => 0,
            'data' => $results
        ]);
    }

    /**
     * 获取抽奖记录（单活动模式）
     */
    public function records(Request $request): Response
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 10);

        // 单活动模式，获取所有抽奖记录
        $records = DrawRecord::getList($page, $pageSize);

        return success($records);
    }

    /**
     * 获取指定轮次的抽奖记录（单活动模式）
     */
    public function getRecordsByRound(Request $request, int $round): Response
    {
        if (!$round) {
            return json(['code' => 400, 'message' => '轮次不能为空']);
        }

        // 单活动模式，直接根据轮次查询
        $records = DrawRecord::where('round', $round)->select();

        // 关联用户和奖品信息
        foreach ($records as &$record) {
            $record->user = User::find($record->user_id);
            if ($record->prize_id) {
                $record->prize = Prize::find($record->prize_id);
            }
        }

        return json([
            'code' => 0,
            'data' => $records
        ]);
    }

    /**
     * 重置抽奖
     */
    public function reset(Request $request): Response
    {
        // 重置用户的中奖状态
        User::where('is_winner', 1)->update(['is_winner' => 0]);

        // 清空抽奖记录
        DrawRecord::truncate();

        return json(['code' => 0, 'message' => '重置成功']);

        // 关联用户和奖品信息
        foreach ($records as &$record) {
            $record->user = User::find($record->user_id);
            if ($record->prize_id) {
                $record->prize = Prize::find($record->prize_id);
            }
        }

        return json([
            'code' => 0,
            'data' => $records
        ]);
    }
}
